// app/service/bank_transaction_service.js
'use strict';

const Service = require('egg').Service;

class BankTransactionService extends Service {
  // 获取银行流水列表
  async getTransactionList(page, pageSize, params) {
    const { ctx } = this;
    const { payerName, transactionId, startDate, endDate, supplierId, transactionType } = params;
    
    const query = {
      where: {}
    };
    
    if (transactionId) {
      query.where.transactionId = transactionId;
    }
    
    if (supplierId) {
      // 根据供应商ID获取供应商名称，然后通过供应商名称查询银行流水
      const supplier = await ctx.model.SupplierModel.findByPk(supplierId);
      if (supplier) {
        // 使用精确匹配而不是模糊匹配
        query.where.payerName = supplier.name;
      }
    } else if (payerName) {
      // 对于直接提供的payerName参数，仍然使用模糊匹配
      query.where.payerName = {
        [ctx.app.Sequelize.Op.like]: `%${payerName}%`
      };
    }
    
    if (startDate || endDate) {
      query.where.transactionDate = {};
      
      if (startDate) {
        query.where.transactionDate[ctx.app.Sequelize.Op.gte] = new Date(startDate);
      }
      
      if (endDate) {
        query.where.transactionDate[ctx.app.Sequelize.Op.lte] = new Date(endDate);
      }
    }
    
    // 添加交易类型筛选（收入/支出）
    if (transactionType) {
      if (transactionType === 'income') {
        // 收入：金额大于0
        query.where.amount = { [ctx.app.Sequelize.Op.gt]: 0 };
      } else if (transactionType === 'expense') {
        // 支出：金额小于0
        query.where.amount = { [ctx.app.Sequelize.Op.lt]: 0 };
      }
    }
    
    const result = await ctx.model.BankTransactionModel.findAndCountAll({
      ...query,
      limit: parseInt(pageSize),
      offset: (parseInt(page) - 1) * parseInt(pageSize),
      order: [['transaction_date', 'DESC']]
    });
    
    return {
      list: result.rows,
      total: result.count
    };
  }
  
  // 根据ID获取银行流水
  async getTransactionById(id) {
    const { ctx } = this;
    return await ctx.model.BankTransactionModel.findByPk(id);
  }
  
  // 创建银行流水
  async createTransaction(transactionData) {
    const { ctx } = this;
    return await ctx.model.BankTransactionModel.create(transactionData);
  }
  
  // 更新银行流水
  async updateTransaction(id, transactionData) {
    const { ctx } = this;
    const transaction = await ctx.model.BankTransactionModel.findByPk(id);
    
    if (!transaction) {
      throw new Error('银行流水不存在');
    }
    
    return await transaction.update(transactionData);
  }
  
  // 删除银行流水
  async deleteTransaction(id) {
    const { ctx } = this;
    const transaction = await ctx.model.BankTransactionModel.findByPk(id);
    
    if (!transaction) {
      throw new Error('银行流水不存在');
    }
    
    return await transaction.destroy();
  }
}

module.exports = BankTransactionService;